<template>
  <div :style="'width:'+(treeConfig.width+'px')">
    <div class="search" v-if="treeConfig.search == 1">
      <el-input placeholder="关键字搜索" v-model="filterText" clearable>
      </el-input>
    </div>
    <div class="tree">
      <div class="title" v-if="treeConfig.title || toolButOptions.length >0">
        <b style="font-size: 16px" v-if="treeConfig.title">{{ treeConfig.title }}</b>
        <span @click="handleOperationClick('add')" v-if="toolButOptions.map(o=>o.code).indexOf('add') != -1"
              style="position: absolute;right: 5px;font-size: 18px;line-height: 20px;cursor: pointer;">
                    <el-tooltip class="item" effect="dark" content="新增" placement="top">
                      <i class="vxe-icon-add" style="margin-right:5px;"></i>
                    </el-tooltip>
                    </span>
      </div>
      <el-scrollbar style="height: calc(100% - 70px)" v-loading="loading" element-loading-text="正在加载数据中...">
        <el-tree ref="treeBox"
                 :lazy="treeConfig.lazy == 1"
                 :data="data"
                 :load="load"
                 :show-border="false"
                 :expand-on-click-node="treeConfig['expand-on-click-node']"
                 :default-expand-all="treeConfig.lazy == 0 && treeConfig.firstExpandAll == 1"
                 :props="props"
                 v-bind="$attrs"
                 @nodeClick="nodeClick"
                 :show-checkbox="treeConfig.showCheckbox == 1"
                 :highlight-current="true"
                 :filter-node-method="filterNode">
          <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span style="position: absolute;right: 5px">
            <olTableOperate :row="data" :value="toolButOptions"
                            @handleOperationClick="handleOperationClick($event)"></olTableOperate>
          </span>
        </span>
          </template>
        </el-tree>
      </el-scrollbar>
    </div>
    <olForm ref="form" @query="doQuery"></olForm>
  </div>
</template>

<script>

import olTableOperate from "@/components/table/ol-table-operate/index.vue";
import {handleTree} from "@/utils/tree";
import {fillTemplate} from "@/utils/object";
import olForm from "@/components/table/ol-form/index.vue";
import {post} from "@/utils/http/httpUtils";
import {error} from "@/utils/msg";

export default {
  name: "oTree",
  components: {olForm, olTableOperate},
  props: {
    treeConfig: {},
    toolButOptions: {},
    formMainList: {}
  },
  inject: ['tableAll', 'http'],
  computed: {
    props() {
      return {
        key: this.treeConfig.value,
        label: this.treeConfig.label,
        children: this.treeConfig.children
      }
    }
  },
  data() {
    return {
      data: [],
      search: '关键字搜索',
      filterText: "",
      loading: false,
      value: '',
    }
  },
  methods: {
    nodeClick(params) {
      if (this.treeConfig.optionJson.eventsValue && this.treeConfig.optionJson.eventsValue['node-click']) {
        eval(this.treeConfig.optionJson.eventsValue['node-click']);
      } else if (this.treeConfig.tableQueryParams) {
        this.doRightTable(params)
      }
    },
    doGetParams(param, v, getParams) {
      let kv = param.split(":");
      if (kv.length == 1) {
        getParams[kv[0]] = v[kv[0]]
      } else {
        if (param.indexOf("$") != -1) {
          getParams[kv[0]] = fillTemplate(kv[1], v)
        } else {
          getParams[kv[0]] = v[kv[1]]
        }

      }
    },
    doRightTable(v) {
      let getParams = {};
      let paramsStr = this.treeConfig.tableQueryParams.trim();
      if (paramsStr.indexOf(",") != -1) {
        let params = paramsStr.split(",");
        for (let param of params) {
          this.doGetParams(param, v, getParams);
        }
      } else {
        this.doGetParams(paramsStr, v, getParams);
      }
      this.tableAll.t1.queryParams(getParams, true);
    },
    async handleOperationClick(e) {
      let {obj, row} = e;
      if (obj.customFunction) {
        eval(obj.customFunction);
      } else if (obj.code == "delete") {
        await this.remove(e);
      } else if (obj.code == 'edit' || obj.code == 'add') {
        let form = {}
        if (obj.code == 'edit') {
          form = this.formMainList.edit
        } else if (obj.code == 'add') {
          form = this.formMainList.add
        }
        let data = {
          type: form.formMain.designer,
          saveUrl: form.formMain.saveUrl,
          formData: row,
          theme: this.theme,
          tableConfigId: this.tableConfigId
        }
        data.form = JSON.parse(form.formJson[data.type == 0 ? 'optionJson' : 'customJson'])
        if (obj.code == 'edit') {
          data.updateKey = form.formMain.updateKey
          this.$refs["form"].init(data, true)
        }
        if (obj.code == 'add') {
          data.formData = {}
          this.$refs["form"].init(data)
        }
      }
      this.$emit("handleOperationClick", e)
    },
    /**
     * 内置删除方法
     * @param o
     * @returns {Promise<void>}
     */
    async remove(o) {
      let {row} = o;
      const type = await this.confirm('数据删除后不可恢复，您确定要删除吗？', '删除提示', 'error')
      if (type != "cancel") {
        /*let params = this.deleteParameter;
        for (let key of Object.keys(this.deleteParameter)) {
          if (key != '$parentId') {
            params[key] = row[key];
          }
        }
        await post(this.http, '/crud/delete', params).then(r => {
          if (r != false) {
            this.query()
          }
        })*/
      }
    },
    load(node, resolve) {
      if (node.level === 0) {
        return;
      } else {
        this.value = node.data[this.treeConfig.value]
      }
      post(this.http, '/online/crud/query', this.getParams()).then(({
                                                                      data,
                                                                      code,
                                                                      msg
                                                                    }) => {
        if (code != 200) {
          error(msg);
          return;
        }
        resolve(data.listData)
      })
    },
    getParams(params) {
      if (!params) {
        params = {
          id: this.treeConfig.uuid,
          queryType: 1,
          enablePage: false
        }
      }
      if (this.value) {
        let lazyValue = this.value.trim();
        if (lazyValue.indexOf("=") != -1) {
          params.executeWhere = lazyValue;
        } else {
          params.executeWhere = this.treeConfig.treeParentId.trim() + "='" + lazyValue + "'";
        }
      }
      return params;
    },
    doQuery(params) {
      this.loading = true;
      post(this.http, '/online/crud/query', this.getParams(params), false, false).then(({
                                                                                          data,
                                                                                          code,
                                                                                          msg
                                                                                        }) => {
        if (code != 200) {
          error(msg);
          return;
        }
        if (this.treeConfig.convertTree == 1) {
          this.data = handleTree(data.listData, this.treeConfig.treeId, this.treeConfig.treeParentId)
        } else {
          this.data = data.listData;
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    filterNode(value, data) {
      if (!this.treeShow) {
        this.treeShow = value;
      }
      if (!value) return true;
      return data[this.treeConfig.label].indexOf(value) !== -1;
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeBox.filter(val);
    }
  }, created() {
    this.$nextTick(() => {
      if (this.treeConfig.autoInit == 1) {
        if (this.treeConfig.lazy == 1 && this.treeConfig.firstLazyValue != '' && this.treeConfig.firstLazyValue != undefined) {
          this.value = this.treeConfig.firstLazyValue.toString().trim();
        }
        this.doQuery();
      }
      this.$emit("initOk")
    })
  },

}

</script>

<style>

</style>
<style lang="scss" scoped>
.search {
  height: 38px;

  div:first-child {
    width: 100%
  }
}

.tree {
  position: relative;
  background-color: white;
  height: 100%;

  .title {
    height: 20px;
    padding: 6px;
    border-bottom: 1px solid #dcdfe685;
    position: relative;

    b {
      position: relative;
      font-size: 14px
    }

    div {
      font-size: 8px;
    }
  }
}
</style>
